package com.example.taobao

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.myaddress.*
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import java.net.URLEncoder
import kotlin.concurrent.thread


class Myaddress : AppCompatActivity() {
    private  var  addresslist:ArrayList<addressinfo> = ArrayList<addressinfo>()
    val handle = @SuppressLint("HandlerLeak")
    object :Handler()
    {
        override fun handleMessage(msg: Message) {
            addresslist.clear()
            addresslist = msg.obj as ArrayList<addressinfo>
            val layoutManager = LinearLayoutManager(this@Myaddress)
            adressrecyclerview.layoutManager = layoutManager
            val adapter = AddressAdapter(addresslist)
            adressrecyclerview.adapter = adapter
            if(!addresslist.isEmpty()) {
                adressrecyclerview.smoothScrollToPosition(addresslist.size - 1)
            }
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.myaddress)

        initData()
        refesh()
        newaddress.setOnClickListener {
            intent.setClass(this@Myaddress,Newaddress::class.java)
            startActivity(intent)
        }
        return3.setOnClickListener {
            intent.setClass(this@Myaddress,zhuyem::class.java)
            startActivity(intent)
        }
    }

    override fun onResume() {
        initData()
        refesh()
        super.onResume()
        initData()
        refesh()
    }

    override fun onRestart() {
        initData()
        refesh()
        super.onRestart()
    }
    fun refesh()
    {
        val layoutManager = LinearLayoutManager(this@Myaddress)
        adressrecyclerview.layoutManager = layoutManager
        val adapter = AddressAdapter(addresslist)
        adressrecyclerview.adapter = adapter
        adapter.notifyDataSetChanged()
    }
    fun tiaoz(meg:ArrayList<String>)
    {
        val bundle = Bundle()
        bundle.putStringArrayList("message",meg)
        val intent: Intent = Intent()
        intent.putExtras(bundle)
        intent.setClass(this@Myaddress,Alteraddress::class.java)
        startActivity(intent)
    }
    private class AddressViewHolder(view: View) : RecyclerView.ViewHolder(view)
    {
        val tvname: TextView =view.findViewById(R.id.tvname)
        val tvsuozaidiqu: TextView =view.findViewById(R.id.tvsuozdiqu)
        val tvxiangxidiz: TextView =view.findViewById(R.id.tvxiangxidiz)
        val tvdelete :ImageButton = view.findViewById(R.id.deleteaddress)
        val tvnumber: TextView =view.findViewById(R.id.tvnumber)
        val alteraddress : ImageButton = view.findViewById(R.id.alteraddress)
    }

    private inner  class AddressAdapter(val addressList: List<addressinfo>) :
        RecyclerView.Adapter<AddressViewHolder>() {
        private var itemClickListener: IKotlinItemClickListener? = null
        override fun getItemCount() = addressList.size
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AddressViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.addressdetal, parent, false)
            return AddressViewHolder(view)
        }

        override fun onBindViewHolder(holder: AddressViewHolder, position: Int) {
            val info = addressList[position]
            var meg11:ArrayList<String> = ArrayList()
            holder.tvname.text = info.name
            holder.tvsuozaidiqu.text = info.suozaidiqu
            holder.tvxiangxidiz.text = info.xiangxidiz
            holder.tvnumber.text = info.phonenumber
            holder.tvdelete . setOnClickListener {
                thread {
                    try {
                        val client = OkHttpClient()
                        val requestBody = FormBody.Builder()
                            .add("name", URLEncoder.encode(info.name, "utf-8"))
                            .build()
                        val request = Request.Builder()
                            .url("http://192.168.43.140:8080/aaa_war_exploded/delete.jsp")
                            .post(requestBody)
                            .build()
                        val respone = client.newCall(request).execute()
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
                addresslist.removeAt(position)
                refesh()
            }
            holder.alteraddress.setOnClickListener {
                meg11.clear()
                meg11.add(info.name)
                meg11.add(info.suozaidiqu)
                meg11.add(info.xiangxidiz)
                meg11.add(info.phonenumber)
                tiaoz(meg11)
            }
            holder.itemView.setOnClickListener {
                meg11.clear()
                meg11.add(info.name)
                meg11.add(info.suozaidiqu)
                meg11.add(info.xiangxidiz)
                meg11.add(info.phonenumber)
                tiaoz(meg11)
            }

        }
        fun setOnKotlinItemClickListener(itemClickListener: IKotlinItemClickListener) {
            this.itemClickListener = itemClickListener
        }

    }


    fun initData() {
        addresslist.clear()
        thread {
            try {
                var addr :ArrayList<addressinfo> = ArrayList<addressinfo>()
                val client = OkHttpClient()
                val request = Request.Builder()
                    .url("http://192.168.43.140:8080/aaa_war_exploded/getall1.jsp")
                    .build()
                val respone = client.newCall(request).execute()
                val responeData = respone.body!!.string()
                addr = parseJosn(responeData)
                val msg = Message()
                msg.obj = addr
                handle.sendMessage(msg)
            }
            catch (e:Exception)
            {
                e.printStackTrace()
            }
        }
    }
    private fun parseJosn(jsonStr:String):ArrayList<addressinfo>
    {
        val address :ArrayList<addressinfo> =  ArrayList<addressinfo>()
        try {
            val jaonArray = JSONArray(jsonStr)
            for (i in 0 until jaonArray.length())
            {
                val jsonObject = jaonArray.getJSONObject(i)
                val id:Int = jsonObject.getInt("id")
                val name = jsonObject.getString("name")
                val phonenumber = jsonObject.getString("phonenumber")
                val suozaidiqu = jsonObject.getString("suozaidiqu")
                val xiangxidiz = jsonObject.getString("xiangxidiz")
                val username = jsonObject.getString("username")
                address.add(addressinfo("${name}","${phonenumber}","${suozaidiqu}","${xiangxidiz}",id,"${username}"))
            }
        }
        catch (e: Exception)
        {
            e.printStackTrace()
        }
        return address
    }

}